﻿//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2020年1月4日 20:25:47
//------------------------------------------------------------

using System;
using System.Collections.Generic;


namespace NKG_MVVM_UI
{
    public class ViewFactory
    {
        public static Dictionary<Type, Queue<AViewLogic>> ViewPool =
            new Dictionary<Type, Queue<AViewLogic>>();

        public static T FetchView<T>() where T : AViewLogic
        {
            AViewLogic tempAView;
            if (ViewPool.TryGetValue(typeof(T), out var tempViewQueue))
            {
                tempAView = tempViewQueue.Dequeue();
                tempAView.OnInit();
                return (T) tempAView;
            }

            //TODO:去加载UI资源，进行实例化
            tempAView = Activator.CreateInstance<T>();
            Queue<AViewLogic> newViewQueue = new Queue<AViewLogic>();
            newViewQueue.Enqueue(tempAView);
            ViewPool.Add(typeof(T), newViewQueue);

            tempAView.OnInit();
            return (T) tempAView;
        }

        /// <summary>
        /// 回收View
        /// </summary>
        /// <param name="aViewLogic"></param>
        public static void RecycleView(AViewLogic aViewLogic)
        {
            aViewLogic.OnRecycle();
            if (ViewPool.TryGetValue(aViewLogic.GetType(), out var tempViewModelQueue))
            {
                tempViewModelQueue.Enqueue(aViewLogic);
            }
            else
            {
                Console.WriteLine($"不应当，一个V对象应该生于工程创建，死于工厂回收，请检查逻辑错误！");
                Queue<AViewLogic> newViewQueue = new Queue<AViewLogic>();
                newViewQueue.Enqueue(aViewLogic);
                ViewPool.Add(aViewLogic.GetType(), newViewQueue);
            }
        }
    }
}